#include "bga/graphics/Shader.h"
#include <iostream>
#include <cstring>
#include <fstream>

using namespace std;

namespace bga
{

Shader::Shader() : GLObject(), filename(""), type(FRAGMENT_SHADER)
{
}

Shader::Shader(const string& filename, TypeShader type) : GLObject(), filename(filename), type(type)
{
    //this->file.open(filename.c_str(), ios::in);
    //this->type = type;
    this->parseShader();
    create();
}

Shader::~Shader()
{
    this->destroy();
}

void Shader::parseShader()
{
    ifstream file(this->filename.c_str(), ios::in);

    string s;

    char line[1024];

    while(file.getline(line,1024))
    {
        this->source += line;
        this->source += '\n';
    }

    file.close();
}

 void Shader::create()
 {
    switch(this->type)
    {
        case VERTEX_SHADER:
            this->id = glCreateShader(GL_VERTEX_SHADER);
            break;

        case FRAGMENT_SHADER:
            this->id = glCreateShader(GL_FRAGMENT_SHADER);
            break;
    }
    if(this->id == 0)
    {
        cout << "Shader creation error" << endl;
    }
 }

 void Shader::compil()
 {

    const char* sourceCode = this->source.c_str();
    glShaderSource(this->id, 1, &sourceCode, NULL);
    glCompileShader(this->id);

    int res;
    glGetShaderiv(this->id, GL_COMPILE_STATUS, &res);

    if(res != GL_TRUE)
    {
        int sizeLog;
        glGetShaderiv(this->id, GL_INFO_LOG_LENGTH, &sizeLog);
        char* log = new char[sizeLog + 1];
        glGetShaderInfoLog(this->id, sizeLog, &sizeLog, log);
        cout << log << endl;
        delete[] log;
    }

 }

void Shader::destroy()
{
    if(id != 0)
        glDeleteShader(this->id);
}

}
